//
//  MsgCommand.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/3/27.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "MsgCommand.h"
#import "UserModel.h"

#import <MessageUI/MessageUI.h>
#import <SVProgressHUD.h>

@interface MsgCommand()<MFMessageComposeViewControllerDelegate,UITextFieldDelegate>

@property (strong, nonatomic) id delegateController;

@property (strong, nonatomic) UserModel *userModel;

@end

@implementation MsgCommand

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

#pragma mark 发送短信
-(void)getMessagePhoneNumberForSerialNumber:(NSString *)serialNumber Delegate:(id)delegate title:(NSString *)title body:(NSString *)body{
    
    if (!serialNumber) {
        
        if (self.userModel.selectedDeviceSerialNumber) {
            
            serialNumber = self.userModel.selectedDeviceSerialNumber;
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            [SVProgressHUD dismissWithDelay:1];
            
            return;
            
        }
        
    }
    
    BOOL isSetPhoneNumber = NO;
    
    if (![self.userModel.msgPhoneNumberDictionary valueForKey:serialNumber]) {
        
        isSetPhoneNumber = YES;
        
    }else{
        
        NSDictionary *dict = [self.userModel.msgPhoneNumberDictionary valueForKey:serialNumber];
        
        NSString *phoneNumberString = [dict valueForKey:DK_PHONE_NUMBER];
        
        if (!(phoneNumberString.length > 0)) {
            
            isSetPhoneNumber = YES;
            
        }
        
    }
    
    if (isSetPhoneNumber) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Setting" message:@"Setting PhoneNumber" preferredStyle:UIAlertControllerStyleAlert];

        
        __block UITextField *countryCodeTextField;
        __block UITextField *phoneNumberTextfield;
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = @"Country Code";
            
            textField.keyboardType = UIKeyboardTypeNumberPad;
            
            textField.delegate = self;
            
            countryCodeTextField = textField;
            
        }];
        
        
        
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = @"Phone Number";
            
            textField.delegate = self;
            
            textField.keyboardType = UIKeyboardTypeNumberPad;
            
            phoneNumberTextfield = textField;
            
        }];
        
        
        
        //确认
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            if (phoneNumberTextfield.text.length > 0) {
                
                NSString *countryCodeString = countryCodeTextField.text;
                 
                NSString *phoneNumberString = phoneNumberTextfield.text;
                
                NSDictionary *msgDictionary = @{DK_COUNTRY_CODE:countryCodeString,DK_PHONE_NUMBER:phoneNumberString};
                
                [self.userModel.msgPhoneNumberDictionary setValue:msgDictionary forKey:serialNumber];
                
                
                
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    
                    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                
                    NSString *filePath = [path stringByAppendingPathComponent:ARCHIVER_MSG_PHONE_NUMBER_DICTIONARY];
                    
                    [NSKeyedArchiver archiveRootObject:self.userModel.msgPhoneNumberDictionary toFile:filePath];
                    
                });
                
                NSString *finalPhoneNumber;
                
                if (countryCodeTextField.text.length > 0) {
                    
                    finalPhoneNumber = [NSString stringWithFormat:@"+%@%@",countryCodeTextField.text,phoneNumberTextfield.text];
                    
                }else{
                    
                    finalPhoneNumber = [NSString stringWithFormat:@"%@%@",countryCodeTextField.text,phoneNumberTextfield.text];
                    
                }
                
                
                
                [self showMessageViewForPhoneNumberArray:@[finalPhoneNumber] title:title body:body delegate:delegate];
                
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"PhoneNumber can't be empty"];
                
                [SVProgressHUD dismissWithDelay:1];
                
            }
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [delegate presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        NSDictionary *dict = [self.userModel.msgPhoneNumberDictionary valueForKey:serialNumber];
        
        NSString *countryCodeString = [dict valueForKey:DK_COUNTRY_CODE];
        NSString *phoneNumberString = [dict valueForKey:DK_PHONE_NUMBER];
        
        NSLog(@"%@%@",countryCodeString,phoneNumberString);
        
        NSString *finalPhoneNumber;
        
        if (countryCodeString.length > 0) {
            
            finalPhoneNumber = [NSString stringWithFormat:@"+%@%@",countryCodeString,phoneNumberString];
            
        }else{
            
            finalPhoneNumber = [NSString stringWithFormat:@"%@%@",countryCodeString,phoneNumberString];
            
        }
        
        
        
        [self showMessageViewForPhoneNumberArray:@[finalPhoneNumber] title:title body:body delegate:delegate];
        
    }
    
    
    
    
    
}

#pragma mark 发送短信
-(void)showMessageViewForPhoneNumberArray:(NSArray *)phoneNumberArray title:(NSString *)title body:(NSString *)body delegate:(id)delegate{
    
    UIAlertController *selectAlertController = [UIAlertController alertControllerWithTitle:@"Warning" message:@"A SMS cost will be charged by the telecom carrier from the current cellphone number,which has to be the same as the registered master number.Otherwise device will not listen and operate this command." preferredStyle:UIAlertControllerStyleAlert];
    
    //确认
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"CONFIRM" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [SVProgressHUD showWithStatus:@"Loading..."];
        
        if( [MFMessageComposeViewController canSendText] )
        {
            
            
            MFMessageComposeViewController * mfMessageComposeViewController = [[MFMessageComposeViewController alloc] init];
            mfMessageComposeViewController.recipients = phoneNumberArray;
            //        controller.navigationBar.tintColor = [UIColor redColor];
            mfMessageComposeViewController.body = body;
            mfMessageComposeViewController.messageComposeDelegate = self;
            self.delegateController = delegate;
            
            [[[[mfMessageComposeViewController viewControllers] lastObject] navigationItem] setTitle:title];//修改短信界面标题
            
            [mfMessageComposeViewController.navigationItem setTitle:title];
            
            [delegate presentViewController:mfMessageComposeViewController animated:YES completion:^{
                
                [SVProgressHUD dismiss];
                
            }];
            
        }
        else
        {
            [SVProgressHUD dismiss];
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Failed" message:@"This device can't send message" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertController addAction:doneAction];
            
            [delegate presentViewController:alertController animated:YES completion:nil];
            
            NSLog(@"can't send message");
            
        }

        
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"CANCEL" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [selectAlertController addAction:confirmAction];
    [selectAlertController addAction:cancelAction];
    
    [delegate presentViewController:selectAlertController animated:YES completion:nil];
    
    }


#pragma mark 发送短信
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self.delegateController dismissViewControllerAnimated:YES completion:nil];
    switch (result) {
        case MessageComposeResultSent:
            //信息传送成功
            NSLog(@"Send Message Success");
            [SVProgressHUD showSuccessWithStatus:@"Success"];
        
            break;
        case MessageComposeResultFailed:
            //信息传送失败
            NSLog(@"Send Message Failed");
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            break;
        case MessageComposeResultCancelled:
            //信息被用户取消传送
            NSLog(@"Send Message Cancel");
            break;
        default:
            break;
    }
    
    self.delegateController = nil;
    
}


#pragma mark 只能输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

@end
